extends Control
@onready var strings: Label = $Strings
@onready var chat_box: Label = $ChatBox

var _strings_queue:Array[String]
var _words_is_displaying:bool = false
var _string_fadeining:bool = false

var _chat_queue:Array[String]
var _chat_fadeining:bool = false


var dialogues:JSON
@export var chat_data_path:String = "res://preferb/words/chat_data.json"
signal finish_dialogue
signal finish_string
var _can_finish_string_emit:bool=false
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	strings.self_modulate.a = 0
	chat_box.visible=false

	var file:=FileAccess.open(chat_data_path,FileAccess.READ)
	dialogues=JSON.new()
	dialogues.parse(file.get_as_text(true))
	
	Global.display_str.connect(display_str)
	Global.display_word.connect(display_word)
	Global.takeplace_dialogue.connect(takeplace_dialogue)
	finish_dialogue.connect(Global.dialogue_finished.emit)
	finish_string.connect(Global.display_string_finished.emit)
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	if not _words_is_displaying and strings.self_modulate.a==0 and _strings_queue.size()!=0:
		strings.text = _strings_queue.pop_front()
		_can_finish_string_emit=true
		strings.self_modulate.a = 0.001
		_string_fadeining = true
	elif strings.self_modulate.a!=0:
		if _string_fadeining:
			strings.self_modulate.a = move_toward(strings.self_modulate.a,0.6,delta)
			if strings.self_modulate.a>=0.6:_string_fadeining = false
		else:
			if _strings_queue.size()==0:
				strings.self_modulate.a = move_toward(strings.self_modulate.a,0,delta/5)
				if strings.self_modulate.a==0 and _can_finish_string_emit:
					_can_finish_string_emit=false
					finish_string.emit()
			else:
				strings.self_modulate.a = move_toward(strings.self_modulate.a,0,delta/3)

	if not _chat_fadeining and chat_box.visible==false and _chat_queue.size()!=0:
		chat_box.text = _chat_queue.pop_front()
		print(chat_box.text)
		chat_box.visible_ratio=0
		chat_box.visible=true
		_chat_fadeining=true
	elif chat_box.visible==true:
		if chat_box.visible_ratio!=1:chat_box.visible_ratio = move_toward(chat_box.visible_ratio,1,10*delta/chat_box.text.length())

func display_str(stri:String)->void:
	_strings_queue.push_back(stri)

func display_word(stri:String)->void:
	if stri!="":_chat_queue.push_back(stri)
	else:
		if _chat_fadeining and chat_box.visible_ratio!=1:
			chat_box.visible_ratio=1
		elif _chat_fadeining and chat_box.visible_ratio==1:
			_chat_fadeining=false
			chat_box.visible = false
			if _chat_queue.size()==0:finish_dialogue.emit()

func takeplace_dialogue(dialogue_name:String)->bool:
	if not dialogues:return false
	if not dialogues.data is Dictionary:return false
	if dialogue_name in dialogues.data:
		for stri in dialogues.data[dialogue_name]:
			if stri is String and not stri=="":
				display_word(stri)
		return true
	return false
